package com.demo.dao.impl;

import com.demo.dao.UserDao;
import com.demo.domain.User;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import java.util.List;

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
    @Override
    public User getByUserCode(User user) {
        // 调用方法可以得到HibernateTemplate对象
        HibernateTemplate hibernateTemplate = this.getHibernateTemplate();
        // 登录的查询操作
        // 根据用户名和密码查询
        List<User> list = (List<User>) this.getHibernateTemplate().find(
                "from User where user_name=? and user_password=?",
                user.getUser_name(), user.getUser_password());
        // 返回user对象
        // 如果查询之后，没有结果，list中没有值，根据get(下标)获取不到值，出现下标越界异常
        // 判断
        if (list != null && list.size() != 0) {
            User u = list.get(0);
            return u;
        }

        return null;
    }

//    public User getByUserCode(final String code) {
//        // hql
//        return getHibernateTemplate().execute(new HibernateCallback<User>() {
//
//            public User doInHibernate(Session session)
//                    throws HibernateException {
//                String hql = "from User where user_code=?";
//                Query query = session.createQuery(hql);
//                query.setParameter(0, code);
//                User user = (User) query.uniqueResult();
//                return user;
//            }
//        });
//    }
}
